<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\common\controller\AdminBaseController;
use app\common\model\AdminAuthGroupModel;
use app\common\model\AdminAuthRuleModel;
use app\common\model\AdminConfigModel;
use app\common\model\AdminModel;
use app\common\model\ArticleCategoryModel;
use app\common\model\ArticleModel;
use think\cache\driver\Redis;
use think\captcha\facade\Captcha;
use think\facade\Config;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;

class IndexController extends AdminBaseController
{

    public function index()
    {
        $data = Request::header('Authorization');
        return json(['status'=>false, 'info'=>'error', 'data'=>['data'=>$data]]);
    }

    /**
     * 验证码
     * @return \think\Response
     */
    public function verify()
    {
        return Captcha::createApi('base64');
    }

    /**
     * 校验验证码
     * @return \think\response\Json
     */
    public function checkCaptcha()
    {
        $captcha  = input('captcha');
        $captchaKey  = input('captchaKey');

        if(!Captcha::checkApi(strval($captcha), $captchaKey)){
            return json(['status'=>false, 'info'=>'验证码错误']);
        }

        return json(['status'=>false, 'info'=>'验证成功']);
    }

    /**
     * 登录接口
     */
    public function login()
    {
        $username = input('username');
        $password = input('password');
        $captcha  = input('captcha');
        $captchaKey  = input('captchaKey');

        if(!Captcha::checkApi(strval($captcha), $captchaKey)){
            return json(['status'=>false, 'info'=>'验证码错误']);
        }

        $admin = AdminModel::where(['username'=>$username])->find();
        if(!$admin){
            return json(['status'=>false, 'info'=>'用户不存在']);
        }
        //验证密码
        if($admin['password'] !== strongmd5($password . $admin['salt'])){
            return json(['status'=>false, 'info'=>'密码错误']);
        }
        $admin['token'] = signToken($admin['id']);
        if(!$admin['token']){
            return json(['status'=>false, 'info'=>'登录验证失败']);
        }

        // 更新用户登录
        $data = [
            'token'     => $admin['token'],
            'logintime' => time(),
            'loginip'   => request()->ip()
        ];
        AdminModel::editUser(['id'=>$admin['id']], $data);

        $admin_user = [
            'id' => $admin['id'],
            'username' => $admin['username'],
            'nickname' => $admin['nickname'],
            'group_id' => $admin['group_id'],
            'avatar' => $admin['avatar'],
            'token' => $admin['token']
        ];

        return json(['status'=>200, 'info'=>'登录成功', 'data'=>['admin'=>$admin_user]]);
    }


    /**
     * 菜单
     * @return \think\response\Json
     */
    public function menus()
    {
        $where[][] = ['type', 'in', '1,2'];
        $where[][] = ['status', 'in', '1'];

        $admin = $this->admin_user['group_id'];
        if($admin !== 1){
            // 权限id
            $admin_auth_group = AdminAuthGroupModel::findByUsername('id', $admin);
            $rule_id = $admin_auth_group['rules'];
            $where[][] = ['id', 'in', $rule_id];
        }

        $arr = AdminAuthRuleModel::list($where, false);
        $list = AdminAuthRuleModel::getTree($arr->toArray());
        return json(['status'=>200, 'info'=>'权限菜单', 'data'=>['menus'=>$list]]);
    }

    /**
     * 用户列表
     */
    public function adminList()
    {
        $where = [];
        $pagenum = input('pagenum');
        $pagesize = input('pagesize');
        $query  = input('query');
        if($query){
            $where[]    = ["nickname" , "like", "$query%"];
        }

        $result= AdminModel::list($where, $pagenum, $pagesize)->toArray();
        $admin_list = $result['data'];
        $total = $result['total'];

        //角色组
        $group_list = AdminAuthGroupModel::list([], 0, 0, false);

        return json(['status'=>200, 'info'=>'管理员列表', 'data'=>['AdminList'=>$admin_list, 'total'=>$total, 'groupList'=>$group_list]]);
    }


    public function addAdmin()
    {
        $username   = input('username');
        $password   = input('password');
        $group_id   = input('group_id');
        $nickname   = input('nickname');
        $email      = input('email');
        $mobile      = input('mobile');
        $status     = 1;
        $salt       = generate_password(4);

        //验证
        if(!$username || !$password || !$group_id){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        //检查用户名是否存在
        $admin = AdminModel::findByUsername('username', $username);
        if($admin){
            return json(['status'=>false, 'info'=>'管理员已经存在']);
        }

        $data = [
            'username'  => $username,
            'password'  => strongmd5($password . $salt),
            'group_id'  => $group_id,
            'nickname'  => $nickname,
            'email'     => $email,
            'mobile'     => $mobile,
            'status'    => $status,
            'salt'      => $salt
        ];
        $result = AdminModel::addUser($data);
        if(!$result){
            return json(['status'=>false, 'info'=>'新增管理员失败']);
        }

        return json(['status'=>200, 'info'=>'新增成功']);
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function getAdmin()
    {
        $id = input('id');

        if(!$id){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        $admin_info              = AdminModel::findByUsername('id', $id);
        if(!$admin_info){
            return json(['status'=>false, 'info'=>'获取用户信息失败']);
        }

        return json(['status'=>200, 'info'=>'用户信息', 'data'=>['adminInfo'=>$admin_info]]);
    }

    /**
     * 编辑管理员
     * @return \think\response\View
     */
    public function saveAdmin()
    {
        //保存信息
        $id             = input('id');
        $group_id       = input('group_id');
        $nickname       = input('nickname');
        $email          = input('email');
        $mobile         = input('mobile');

        //验证
        if(!$group_id){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        $data = [
            'id'        => $id,
            'group_id'  => $group_id,
            'nickname'  => $nickname,
            'email'     => $email,
            'mobile'    => $mobile,
        ];
        $result         = AdminModel::editUser(['id'=>$data['id']], $data);
        if(!$result){
            return json(['status'=>false, 'info'=>'编辑管理员失败']);
        }

        return json(['status'=>200, 'info'=>'编辑成功']);
    }

    /**
     * 删除管理员
     */
    public function delAdmin()
    {
        $id = input('id');
        if(!$id){
            return json(['status'=>false, 'info'=>'id参数错误']);
        }
        if($id == 1){
            return json(['status'=>false, 'info'=>'超级管理员不可删除']);
        }

        $result = AdminModel::del(['id'=>$id]);

        if(!$result){
            return json(['status'=>false, 'info'=>'管理员删除失败']);
        }

        return json(['status'=>200, 'info'=>'管理员删除成功']);
    }

    /**
     * 角色列表
     */
    public function authGroupList()
    {
        $where = [];
        $pagenum = input('pagenum');
        $pagesize = input('pagesize');
        $query  = input('query');
        if($query){
            $where[]    = ["title" , "like", "$query%"];
        }

        $result= AdminAuthGroupModel::list($where, $pagenum, $pagesize)->toArray();
        $auth_group_list = $result['data'];
        $total = $result['total'];


        return json(['status'=>200, 'info'=>'角色列表', 'data'=>['authGroupList'=>$auth_group_list, 'total'=>$total]]);
    }

    /**
     * 添加角色组
     */
    public function addAuthGroup()
    {
        $title = input('title');
        $description = input('description');

        if(!$title){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        $info = AdminAuthGroupModel::findByUsername('title', $title);
        if($info){
            return json(['status'=>false, 'info'=>'角色名称已存在']);
        }

        $data = [
            'title' => $title,
            'description' => $description
        ];

        $result = AdminAuthGroupModel::addPost($data);
        if(!$result){
            return json(['status'=>false, 'info'=>'添加失败']);
        }

        return json(['status'=>200, 'info'=>'添加成功']);
    }

    /**
     * 获取角色组
     */
    public function getAuthGroup()
    {
        $id = input('id');

        if(!$id){
            return json(['status'=>false, 'info'=>'id不能为空']);
        }

        $info = AdminAuthGroupModel::findByUsername('id', $id);
        if(!$info){
            return json(['status'=>false, 'info'=>'获取信息失败']);
        }

        return json(['status'=>200, 'info'=>'success', 'data'=>['editAuthGroupForm'=>$info]]);
    }

    /**
     * 保存角色组
     */
    public function saveAuthGroup()
    {
        $id = input('id');
        $title = input('title');
        $description = input('description');

        if(!$id || !$title){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        $data = [
            'title' => $title,
            'description' => $description
        ];

        $result = AdminAuthGroupModel::editSave(['id'=>$id], $data);
        if(!$result){
            return json(['status'=>false, 'info'=>'保存失败']);
        }

        return json(['status'=>200, 'info'=>'保存成功']);
    }

    /**
     * 删除角色组
     */
    public function delAuthGroup()
    {
        $id = input('id');
        if(!$id){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }
        if($id == 1){
            return json(['status'=>false, 'info'=>'超级管理员不可删除']);
        }

        $result = AdminAuthGroupModel::del(['id'=>$id]);
        if(!$result){
            return json(['status'=>false, 'info'=>'删除失败']);
        }

        return json(['status'=>200, 'info'=>'删除成功']);
    }

    /**
     * 获取权限列表
     */
    public function authRuleList()
    {
        $status = input('status');
        $where = [];
        if($status){
            $where['status'] = $status;
        }

        // 权限列表
        $all_auth = AdminAuthRuleModel::list($where, false);
        $auth_list = AdminAuthRuleModel::getTree($all_auth->toArray());

        // 权限菜单
        $menu_where[][] = ['type', 'in', '1,2'];
        $menu_where[][] = ['status', 'in', '1'];
        $menu = AdminAuthRuleModel::list($menu_where, false);
        $menu_list = AdminAuthRuleModel::getTree($menu->toArray());

        $redis = new Redis();
        $redis->set('hVb9gdSkm_R0CrEqcfmVkoe1DS8', '');

        return json(['status'=>200, 'info'=>'权限菜单', 'data'=>['authRuleList'=>$auth_list, 'authRuleMenu'=>$menu_list]]);
    }

    /**
     * 添加权限节点
     */
    public function addAuthRule()
    {
        $name   = input('name'); // 名称
        $path   = input('path'); // 节点路径
        $icon   = input('icon'); // 图标
        $pid    = input('pid'); // 父级节点id
        $type   = input('type'); // 类型：1菜单，2操作，3方法
        $status = input('status'); // 状态

        if(!$name || !$path || !$type){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        $data = [
            'name'  => $name,
            'path'  => $path,
            'icon'  => $icon,
            'pid'   => $pid,
            'type'  => $type,
            'status'=>$status
        ];

        $result = AdminAuthRuleModel::addPost($data);
        if(!$result){
            return json(['status'=>false, 'info'=>'添加失败']);
        }

        return json(['status'=>200, 'info'=>'添加成功']);
    }

    /**
     * 获取节点信息
     */
    public function getAuthRule()
    {
        $id = input('id');

        if(!$id || !is_numeric($id)){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        $auth_rule_info = AdminAuthRuleModel::findByUsername('id', $id);
        if(!$auth_rule_info){
            return json(['status'=>false, 'info'=>'节点不存在']);
        }

        // 查询出父级节点名称
        $auth_rule_info['pidName'] = '一级菜单';
        if($auth_rule_info['pid'] != 0){
            $pid_result = AdminAuthRuleModel::findByUsername('id', $auth_rule_info['pid']);
            $auth_rule_info['pidName'] = $pid_result['name'];
        }

        return json(['status'=>200, 'info'=>'success', 'data'=>['authRuleInfo'=>$auth_rule_info]]);
    }

    /**
     * 保存节点信息
     */
    /**
     * 添加权限节点
     */
    public function saveAuthRule()
    {
        $id     = input('id'); //节点id
        $name   = input('name'); // 名称
        $path   = input('path'); // 节点路径
        $icon   = input('icon'); // 图标
        $pid    = input('pid'); // 父级节点id
        $type   = input('type'); // 类型：1菜单，2操作，3方法
        $status = input('status'); // 状态

        if(!$name || !$path || !$type || !$id){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        $data = [
            'name'  => $name,
            'path'  => $path,
            'icon'  => $icon,
            'pid'   => $pid,
            'type'  => $type,
            'status'=>$status
        ];

        $result = AdminAuthRuleModel::editSave(['id'=>$id], $data);
        if(!$result){
            return json(['status'=>false, 'info'=>'保存失败']);
        }

        return json(['status'=>200, 'info'=>'保存成功']);
    }

    /**
     * 删除权限节点
     */
    public function delAuthRule()
    {
        $id = input('id');
        if(!$id){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        $reuslt = AdminAuthRuleModel::del(['id'=>$id]);
        if(!$reuslt){
            return json(['status'=>false, 'info'=>'删除失败']);
        }

        return json(['status'=>200, 'info'=>'删除成功']);
    }

    /**
     * 获取角色权限
     */
    public function selectAuthGroup()
    {
        $id = input('id');
        if(!$id){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        $auth_rule_info = AdminAuthGroupModel::findByUsername('id', $id);
        $where[] = ['id', 'in', $auth_rule_info['rules']];
        $auth_rule_list = AdminAuthRuleModel::list($where, false);
        $select_auth_rule = [];
        foreach ($auth_rule_list as $k=>$v){
            if($v['type'] == 3){
                array_push($select_auth_rule, $v['id']);
            }
        }
//        $select_auth_rule = implode(',', $select_auth_rule);
        return json(['status'=>200, 'info'=>'success', 'data'=>['selectAuthRule'=>$select_auth_rule]]);
    }

    /**
     * 保存角色组权限
     */
    public function saveAuthGroupRolePermission()
    {
        $id = input('id');
        $rules = input('ruleIds');

        if(!$id){
            return json(['status'=>false, 'info'=>'参数不能为空']);
        }

        $result = AdminAuthGroupModel::editSave(['id'=>$id], ['rules'=>$rules]);
        if(!$result){
            return json(['status'=>false, 'info'=>'修改权限失败']);
        }

        return json(['status'=>200, 'info'=>'修改成功']);
    }

    /**
     * 文章列表
     */
    public function getArticleList()
    {
        $where = [];
        $pagenum = input('pagenum');
        $pagesize = input('pagesize');
        $query  = input('query');
        if($query){
            $where[]    = ["keywork|title|content" , "like", "$query%"];
        }

        $result= ArticleModel::list($where, $pagenum, $pagesize)->toArray();
        $article_list = $result['data'];
        $total = $result['total'];

        //状态转换为 true ,false
        foreach ($article_list as $k=>$v){
            if($v['status'] == 1){
                $article_list[$k]['status'] = true;
            } else {
                $article_list[$k]['status'] = false;
            }
        }

        // 获取文章分类列表
        $article_categroy_list = ArticleCategoryModel::list([], '','', false);

        return json(['status'=>200, 'info'=>'管理员列表', 'data'=>['articleList'=>$article_list, 'total'=>$total, 'articleCategoryList'=>$article_categroy_list]]);
    }

    /**
     * 修改文章状态
     */
    public function articleStatus()
    {
        $id = input('id');
        $status = input('status');

        if(!$id){
            return json(['status'=>false, 'info'=>'参数不能为空', 'status'=>$status]);
        }

        $result = ArticleModel::saveArticle(['id'=>$id], ['status'=>$status]);
        if(!$result){
            return json(['status'=>false, 'info'=>'更新失败']);
        }

        return json(['status'=>200, 'info'=>'更新成功']);
    }

    /**
     * 添加文章
     */
    public function addArticle()
    {
        $title      = input('title');
        $cate_id    = input('cate_id');
        $keywork    = input('keywork');
        $status     = input('status');
        $sort       = input('sort');
        $content    = input('content');
        $create_time= time();

        if(!$title){
            return json(['status'=>false, 'info'=>'标题不能为空']);
        }
        if(!$cate_id){
            return json(['status'=>false, 'info'=>'分类不能为空']);
        }
        if(!$keywork){
            return json(['status'=>false, 'info'=>'关键字不能为空']);
        }
        if(!$content){
            return json(['status'=>false, 'info'=>'内容不能为空']);
        }

        $data = [
            'title'     => $title,
            'cate_id'   => $cate_id,
            'keywork'   => $keywork,
            'status'    => $status,
            'sort'      => $sort,
            'content'   => $content,
            'create_time' => $create_time
        ];

        $result = ArticleModel::addArticle($data);
        if(!$result){
            return json(['status'=>false, 'info'=>'文章添加失败']);
        }

        return json(['status'=>200, 'info'=>'文章添加成功']);
    }

    /**
     * 查询单篇文章
     */
    public function editArticle()
    {
        $id = input('id');
        if(!$id){
            return json(['status'=>false, 'info'=>'文章id不存在']);
        }

        $article = ArticleModel::findById(['id'=>$id]);
        if(!$article){
            return json(['status'=>false, 'info'=>'文章不存在']);
        }

        return json(['status'=>200, 'info'=>'success', 'data'=>['editForm'=>$article]]);
    }

    /**
     * 保存编辑文章
     */
    public function saveArticle()
    {
        $id         = input('id');
        $title      = input('title');
        $cate_id    = input('cate_id');
        $keywork    = input('keywork');
        $status     = input('status');
        $sort       = input('sort');
        $content    = input('content');
        $update_time= time();

        if(!$id){
            return json(['status'=>false, 'info'=>'id不能为空']);
        }
        if(!$title){
            return json(['status'=>false, 'info'=>'标题不能为空']);
        }
        if(!$cate_id){
            return json(['status'=>false, 'info'=>'分类不能为空']);
        }
        if(!$keywork){
            return json(['status'=>false, 'info'=>'关键字不能为空']);
        }
        if(!$content){
            return json(['status'=>false, 'info'=>'内容不能为空']);
        }

        $data = [
            'title'     => $title,
            'cate_id'   => $cate_id,
            'keywork'   => $keywork,
            'status'    => $status,
            'sort'      => $sort,
            'content'   => $content,
            'update_time' => $update_time
        ];

        $result = ArticleModel::saveArticle(['id'=>$id], $data);
        if(!$result){
            return json(['status'=>false, 'info'=>'文章修改失败']);
        }

        return json(['status'=>200, 'info'=>'文章修改成功']);
    }

    public function delArticle()
    {
        $id = input('id');
        if(!$id){
            return json(['status'=>false, 'info'=>'id不存在']);
        }

        $result = ArticleModel::del(['id'=>$id]);
        if(!$result){
            return json(['status'=>false, 'info'=>'删除失败']);
        }

        return json(['status'=>200, 'info'=>'删除成功']);
    }

    /**
     * 系统配置信息
     */
    public function config()
    {
        $config = AdminConfigModel::selectAll([]);

        return json(['status'=>200, 'info'=>'success', 'data'=>['config'=>$config]]);
    }

    /**
     * 图片上传
     */
    public function adminUpload()
    {
        $file = request()->file('file');
        $status = 200;
        $message = 'success';
        $savename = '';

        try{
            validate(['file'=>[
                'fileSize'  => 410241024,
                'fileExt'   => 'jpg,jpeg,png,bmp,gif',
                'fileMime'  => 'image/jpeg,image/png,image/gif', //这个一定要加上很重要！
            ]])->check(['file'=>$file]);

            //修改上传路径：config/filesystem.php
            //use think\facade\Filesystem;
            $savename       = Filesystem::disk('public')->putFile('admin', $file, 'data');
        }catch (\think\Exception $e){
            $status         = false;
            $message        = $e->getMessage();
        }

        return json(['status'=>$status, 'info'=>$message, 'data'=>['tmp_path'=>$savename]]);
    }

    /**
     * 保存系统配置信息
     */
    public function saveConfig()
    {
        $post_data = input('post.');

        $config = [
        'web_site_title'    => $post_data['web_site_title'],
        'web_site_logo'     =>$post_data['web_site_logo'],
        'web_site_keywords' =>$post_data['web_site_keywords'],
        'web_site_description'=> $post_data['web_site_description'],
        'web_site_copyright'=> $post_data['web_site_copyright'],
        'web_site_icp'      => $post_data['web_site_icp'],
        'web_code_statistics'=> $post_data['web_code_statistics'],
        'web_site_status'   => $post_data['web_site_status']
        ];

        // 保存
        foreach ($config as $k=>$v){
            AdminConfigModel::saveFiled($k, $v);
        }

        return json(['status'=>200, 'info'=>'保存成功']);
    }
}
